package com.dingding.service.activity.core.biz.impl;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.dingding.common.core.beans.ActivityRelUser;
import com.dingding.common.core.beans.IntegralActivity;
import com.dingding.common.core.beans.PresentCondition;
import com.dingding.facade.account.integral.dto.UserInregralOperateDTO;
import com.dingding.facade.account.integral.enums.IntegralTradeContentEnum;
import com.dingding.facade.account.integral.service.IUserIntegralService;
import com.dingding.facade.user.dto.GetUserAttachedDTO;
import com.dingding.facade.user.service.IUserAttachedFacade;
import com.dingding.facde.activity.dto.AttendActivityDTO;
import com.dingding.service.activity.core.biz.IActivityRelUserService;
import com.dingding.service.activity.core.biz.IntegralActivityService;
import com.dingding.service.activity.core.dao.IActivityRelUserDao;
import com.dingding.service.activity.core.dao.IPreferentialActivityDao;
import com.dingding.service.activity.core.dao.IPresentConditionDao;
import com.dingding.service.activity.core.dao.IntegralActivityDao;

/**
 * 
 * @ClassName: IntegralActivityServiceImpl
 * @Description: 积分优惠活动service
 * @author CHEHAUNBO
 * @date 2016年4月1日 上午11:56:58
 * 
 */
@Component("integralActivityService")
public class IntegralActivityServiceImpl implements IntegralActivityService {

	private static final Logger log = Logger.getLogger(IntegralActivityServiceImpl.class);
	/**
	 * 积分优惠活动DAO
	 */
	@Resource(name = "integralActivityDao")
	private IntegralActivityDao integralActivityDao;

	/**
	 * 积分赠送等级DAO
	 */
	@Resource(name = "presentConditionDao")
	private IPresentConditionDao presentConditionDao;

	/**
	 * 用户和活动关联关系DAO
	 */
	@Resource(name = "activityRelUserDao")
	private IActivityRelUserDao activityRelUserDao;

	/**
	 * 优惠活动DAO
	 */
	@Resource(name = "preferentialActivityDao")
	private IPreferentialActivityDao preferentialActivityDao;

	/**
	 * 用户账户积分服务接口
	 */
	@Resource(name = "userIntegralService")
	private IUserIntegralService userIntegralService;

	/**
	 * 用户附属属性操作服务接口
	 */
	@Resource(name = "userAttachedFacade")
	private IUserAttachedFacade userAttachedFacade;

	/**
	 * 用户和活动关联关系服务接口
	 */
	@Resource(name = "activityRelUserService")
	private IActivityRelUserService activityRelUserService;

	/**
	 * 
	 * @Title: attendAvtivity
	 * @Description: 用户参加活动
	 * @param attendActivityDTO
	 *            用户参加活动数据传输DTO
	 * @return boolean true 成功 false 失败
	 * @author CHEHAUNBO
	 * 
	 */
	@Override
	public BigDecimal attendAvtivity(AttendActivityDTO attendActivityDTO) {
		log.info("自动取消，用户参加活动,attendAvtivity");
		BigDecimal totalIntegral = new BigDecimal(0);

		// 用户ID
		String userId = attendActivityDTO.getUserId();
		// 用户参与活动类型
		int attendType = attendActivityDTO.getAttendType();

		// 获取所有的积分优惠活动
		List<IntegralActivity> integralActivities = integralActivityDao.getIntegralActivityList();
		// 获取到所有的积分赠送等级
		List<PresentCondition> presentConditions = presentConditionDao.getPresentConditionList();

		for (IntegralActivity integralActivitie : integralActivities) {
			// 是否受次数限制
			int isFrequencyLimit = integralActivitie.getIsFrequencyLimit();
			// 活动ID
			String activityId = integralActivitie.getIntegralActivityId();
			// 每人参加次数
			int timeLimit = integralActivitie.getTimeLimit();

			int draw = 0; // 当前活动参加次数

			if (isFrequencyLimit == 2) { // 受次数限制
				// 获取用户参加活动次数
				ActivityRelUser activityRelUser = activityRelUserDao.getActivityRelUser(userId, activityId, 1, true);
				if (activityRelUser != null) {
					// 用户领取积分次数
					draw = activityRelUser.getDrawNumber();
					if (draw >= timeLimit) { // 已经达到上线领取次数
						return new BigDecimal(0);
					}
				}
			}

			int type = 0; // 参加条件

			UserInregralOperateDTO userInregralOperateDTO = new UserInregralOperateDTO();
			if (draw == 0 && attendType == 1) { // 首次下单
				userInregralOperateDTO.setTradContent(IntegralTradeContentEnum.Sign.getcontent());
				type = 1;
			} else if (draw > 0 && attendType == 1) { // 不是首次下单
				userInregralOperateDTO.setTradContent(IntegralTradeContentEnum.CompleteOrder.getcontent());
				type = 2;
			} else if (attendType == 2) { // 自动取消订单
				userInregralOperateDTO.setTradContent(IntegralTradeContentEnum.OrderReward.getcontent());
				type = 3;
			}

			log.info("活动类型为：" + type);
			// 查找应赠送积分数
			for (PresentCondition condition : presentConditions) {
				int presentCondition_2 = condition.getPresentCondition();
				if (presentCondition_2 == type) {
					// 获取应赠送积分数
					BigDecimal complimentaryPoints = condition.getComplimentaryPoints();

					userInregralOperateDTO.setUserId(userId);
					userInregralOperateDTO.setIntegral(complimentaryPoints);
					try {
						// 积分累加
						totalIntegral = totalIntegral.add(complimentaryPoints);
						log.info("赠送积分值为：" + complimentaryPoints);
						log.info("赠送后的积分值为：" + totalIntegral);
						// 增加积分
						userIntegralService.addUserInregral(userInregralOperateDTO);

						if (type == 1) {
							// 更改用户状态为已签到
							GetUserAttachedDTO userAttachedDTO = new GetUserAttachedDTO();
							userAttachedDTO.setUserId(userId);
							userAttachedFacade.attendActivity(userAttachedDTO);
						}

						// 更改用户添加活动次数
						activityRelUserService.addAttendActivityNumber(userId, activityId, 1);

					} catch (Exception e) {
						log.error("调用积分赠送服务出现异常！", e);
					}

					break;
				}
			}
		}
		return totalIntegral;
	}

	/**
	 * @Title: resetInvalidActivity
	 * @Description: 重置无效活动
	 * @author yuHaiQing
	 * @return boolean true:重置成功 false:重置失败
	 */
	@Override
	public boolean resetInvalidActivity() {

		return integralActivityDao.resetInvalidIntegralActivity();
	}

	/**
	 * @Title: resetPreferentialActivity
	 * @Description: 重置无效优惠活动
	 * @author yuHaiQing
	 * @return boolean true:重置成功 false:重置失败
	 */
	@Override
	public boolean resetPreferentialActivity() {

		return preferentialActivityDao.resetPreferentialActivity();
	}

	/**
	 * @Title: resetActivityLimitNumber
	 * @Description: 重置活动限制次数（如果该活动参数次数按每天参与次数的话）
	 * @author yuHaiQing
	 * @return boolean true:重置成功 false:重置失败
	 */
	@Override
	public boolean resetActivityLimitNumber() {

		return integralActivityDao.resetActivityLimitNumber();
	}

}
